package com.sun.huazhi.aitaskservice.common.config;

import jakarta.annotation.PostConstruct;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "temp.file")
@Data
public class TempFileConfig {
    private String dir;  // 改为String类型更灵活
    private String prefix = "generated-";
    private boolean autoCleanup = true;

    @PostConstruct
    public void init() throws IOException {
        Path path = Paths.get(this.dir);

        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
                log.info("Created temp directory: {}", path.toAbsolutePath());
            } catch (IOException e) {
                log.error("Failed to create temp directory: " + path, e);
                throw e; // 重新抛出异常确保启动失败
            }
        }

        // 验证目录可写
        Path testFile = path.resolve(".temp-write-test");
        try {
            Files.write(testFile, "test".getBytes(),
                    StandardOpenOption.CREATE,
                    StandardOpenOption.DELETE_ON_CLOSE);
        } catch (IOException e) {
            throw new IllegalStateException("Temp directory not writable: " + path, e);
        }
    }
}